package Array;

public class ErFenChaZhao {
    public static void main(String[] args) {
        //二分查找前提是数组是有序的,
        int [] arr={10,20,30,40,50,60,70,80,90};
        int index= GetIndexByElE(arr,50);
        System.out.println("该元素在数组中的索引为："+index);
    }

    public static int GetIndexByElE(int [] arr,int ele) {
        //定义最小，中间和最大索引
        int minIndex = 0;
        int maxIndex = arr.length - 1;
        int centerIndex = (minIndex + maxIndex) / 2;
        while (minIndex <= maxIndex) {
            if (ele == arr[centerIndex]) {
                return (centerIndex);
            } else if (ele > arr[centerIndex]) {
                minIndex = centerIndex + 1;
            } else if (ele < arr[centerIndex]) {
                maxIndex = centerIndex - 1;
            }
            centerIndex=(minIndex + maxIndex) / 2;

        }
        return -1;//没找到返回-1
    }
}
